<template>
    <div>
        <h2>1.使用场景:当前一个选项等于某一个值得时候,下一个选项才是必填项目:form表单该如何验证;</h2>
        <h2>2.使用场景:如何给某一个字段在完成某种操作后，单独验证；实现选择后立即执行验证(选择完具体位置后；获取了经纬度和位置信息；直接进行表单单独验证功能)</h2>
        <h2>3.使用场景:高德地图得使用：包括(地图得渲染;锚点标记；通过经纬度获取中文位置信息;);使用AMap.Geocoder,在导入地图组件后必须要求输入高德地图配合得密钥；重点这是；不然返回地址失败</h2>
        <hr>
        <h4>需要注意 在el-input 组件上 添加点击使用只能通过@click.native修饰符来实现</h4>
        <el-form label-position="right" label-width="120px" ref="sureFrom" :model="sureFrom" :rules="sureFromRules"
            class="alert_dialog">
            <el-row>
                <el-col :span="24">
                    <el-form-item label="事件确认" prop="eventStatus">
                        <el-select class="name_input" v-model="sureFrom.eventStatus" placeholder="请选择">
                            <el-option v-for="item in confirmList" :key="item.id" :label="item.value" :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="驳回理由"  prop="reason">
                        <el-input type="textarea" :rows="2" placeholder="请输入内容" v-model="sureFrom.reason">
                        </el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="具体位置" prop="event_address" @click.native="selectMap">
                        <el-input v-model="sureFrom.event_address" readonly></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <el-button type="primary" @click="saveSureFun">保 存</el-button>


        <!-- 地图弹框 -->
        <el-dialog title="具体地址" :visible.sync="mapAlertShow" width="700px" append-to-body :close-on-press-escape="false"
            :close-on-click-modal="false" @close="cancelMapAlart">
            <ul class="map_ul">
                <li>经度:{{ this.temporary.longitude }};纬度:{{ this.temporary.latitude }}</li>
                <li>具体地址：{{ this.temporary.event_address }}</li>
            </ul>
            <div id="map"></div>
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="saveMap">保 存</el-button>
                <el-button type="primary" @click="cancelMapAlart">关 闭</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import AMapLoader from "@amap/amap-jsapi-loader";
// web端必须要的 配合key的 密钥，不然就回白屏 同时地址也不会出现
window._AMapSecurityConfig = {
  securityJsCode: "e0274e8e448ad5777897518fc93a7f7c",
};
export default {
    name: 'ElementComponetsQuestionVerify',

    data() {
        return {
            confirmList: [
                { id: 1, value: "确认" },
                { id: 2, value: "取消" },
            ],
            sureFrom: {
                eventStatus: "",
                reason: "",
                // 地图
                longitude: "",
                latitude: "",
                event_address: "",
            },
            sureFromRules: {
                eventStatus: [
                    { required: true, message: "请选择状态", trigger: "change" },
                ],
                reason: [
                    {
                        required: true, message: "请输入驳回理由", trigger: "blur",
                        // 如果需要在特定条件下验证字段，你可以使用 validator 自定义验证规则
                        validator: (rule, value, callback) => {
                            if (this.sureFrom.eventStatus == 2 && !value) {
                                callback(new Error("请输入驳回理由"));
                            } else {
                                callback();
                            }
                        }
                    }
                ],
                event_address: [
                    { required: true, message: "请选择事发地", trigger: "blur" },
                ],
            },
            // 弹框
            mapAlertShow: false,
            temporary: {
                longitude: "",
                latitude: "",
                event_address: "",
            },
            position: [],
        };
    },
    methods: {
        saveSureFun() {
            this.$refs.sureFrom.validate(valid => {
                if (valid) {
                    this.$message.success("通过")
                }
            });
        },
        // 选择具体位置
        selectMap() {
            this.mapAlertShow = true;
            this.initMap();
            if (this.sureFrom.event_address) {
                this.temporary = {
                    longitude: this.sureFrom.longitude,
                    latitude: this.sureFrom.latitude,
                    event_address: this.sureFrom.event_address,
                }
            }
        },
        // 保存地图位置
        saveMap() {
            this.sureFrom.longitude = this.temporary.longitude;
            this.sureFrom.latitude = this.temporary.latitude;
            this.sureFrom.event_address = this.temporary.event_address;
            this.mapAlertShow = false;
            //关键词：validateField 单独去一下 验证event_address 这个字段
            this.$refs.sureFrom.validateField('event_address');
        },
        //取消弹框
        cancelMapAlart() {
            this.mapAlertShow = false;
            this.temporary = {
                longitude: "",
                latitude: "",
                event_address: "",
            };
        },
        // 地图
        // 初始化添加地图
        initMap() {
            AMapLoader.load({
                key: "95a41ea064a9edf07c6647b6d2e5fd59", //此处填入我们注册账号后获取的Key
                version: "2.0", //指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
                plugins: ["AMap.Scale", "AMap.Geocoder"] //需要使用的的插件列表，比例尺'AMap.Scale'  AMap.Geocoder 地图解析
            })
                .then(AMap => {
                    this.map = new AMap.Map("map", {
                        //设置地图容器id
                        viewMode: "3D", //是否为3D地图模式
                        zoom: 16.8, //初始化地图级别
                        center: [114.719899, 41.15901] //初始化地图中心点位置
                    });
                    this.map.on("click", this.showInfoClick);
                    // 如果有数据就渲染
                    if (this.temporary.longitude) {
                        this.drawMark();
                    }
                })
                .catch(e => {
                    console.log(e);
                });
        },
        showInfoClick(e) {
            // 先清除覆盖物
            this.map.clearMap();
            // 获取经纬度
            let lng = e.lnglat.getLng();
            let lat = e.lnglat.getLat();

            this.position = [lng, lat];
            //给经纬度赋值
            this.temporary.longitude = this.position[0];
            this.temporary.latitude = this.position[1];
            // 构造点标记
            var marker = new AMap.Marker({
                icon: "https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png",
                position: this.position,
                anchor: "bottom-center"
            });
            // 给map上添加覆盖物marker
            this.map.add(marker);
            // 让map定位到此位置（有过度效果）
            this.map.setFitView();

            // 创建一个地理编码器实例
            let geocoder = new AMap.Geocoder();
            // 使用地理编码器获取地址
            geocoder.getAddress(this.position, (status, result) => {
                if (status === 'complete' && result.regeocode) {
                    this.temporary.event_address = result.regeocode.formattedAddress;
                } else {
                    this.$message.error("获取地址失败");
                }
            });
        },
        // 绘制已有数据
        drawMark() {
            // 先清除覆盖物
            this.map.clearMap();
            // 构造点标记
            var marker = new AMap.Marker({
                icon: "https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png",
                position: [this.temporary.longitude, this.temporary.latitude],
                anchor: "bottom-center"
            });
            // 给map上添加覆盖物marker
            this.map.add(marker);
            // 让map定位到此位置（有过度效果）
            this.map.setFitView();
        },
    },
};
</script>

<style lang="less" scoped>
// 地图得大小
#map {
  width: 100%;
  height: 600px;
}

.map_ul {
  list-style: none;

  li {
    margin-bottom: 10px;
  }
}
</style>